package cloud.demarcia.rabbitregister.util;

import cloud.demarcia.rabbitregister.constant.RedisConstant;
import cloud.demarcia.rabbitregister.exception.RabbitUtilException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Bojun Wen, wen_bj@outlook.com
 * @date 2022.02.26
 */
@Component
public class RandomCodeManager {

    @Resource
    private StringRedisTemplate template;

    //获取6位验证码
    public String getCode(String email,String prefix){
        String longEmail= prefix+email;
        if(Boolean.TRUE.equals(template.hasKey(longEmail))) {
            throw new RabbitUtilException("验证码获取频繁，请稍后再试");
        }
        String code=generate4digit();
        template.opsForValue().set(longEmail,code,2, TimeUnit.MINUTES);
        return code;
    }
    //生成6位随机数验证码
    private String generate4digit(){
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        return String.valueOf(code);
    }
    //检验验证码是否匹配
    public void matchCode(String email,String code,String prefix){
        String cachedCode=template.opsForValue().get(prefix+email);
        if(cachedCode==null){
            throw new RabbitUtilException("验证码无效，请重新获取");
        }
        if(!cachedCode.equals(code)){
            throw new RabbitUtilException("验证码错误，请确认无误后提交");
        }
    }

}
